import { STORAGE_KEYS } from '@vue-turbo-stack/shared';
import type { User } from '@vue-turbo-stack/shared';

// 认证工具函数
export class AuthUtils {
  // 保存认证信息
  static saveAuth(token: string, user: User) {
    if (typeof window !== 'undefined') {
      localStorage.setItem(STORAGE_KEYS.AUTH_TOKEN, token);
      localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(user));
    }
  }

  // 获取 token
  static getToken(): string | null {
    if (typeof window !== 'undefined') {
      return localStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
    }
    return null;
  }

  // 获取用户信息
  static getUser(): User | null {
    if (typeof window !== 'undefined') {
      const userStr = localStorage.getItem(STORAGE_KEYS.USER_INFO);
      if (userStr) {
        try {
          return JSON.parse(userStr);
        } catch (error) {
          console.error('Failed to parse user info:', error);
          return null;
        }
      }
    }
    return null;
  }

  // 清除认证信息
  static clearAuth() {
    if (typeof window !== 'undefined') {
      localStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
      localStorage.removeItem(STORAGE_KEYS.USER_INFO);
    }
  }

  // 检查是否已认证
  static isAuthenticated(): boolean {
    return !!this.getToken();
  }
}
